package com.gs.core.service;

import java.sql.SQLException;
import java.util.Date;

import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
import org.springframework.transaction.support.TransactionSynchronizationManager;


@Component
@Aspect
public class TransactionCheckAspect {
	
	Logger logger = Logger.getLogger(this.getClass());

	@Before("execution(* com.gs.core.service.ServiceFacade+.save*(*))")
	public void logMessage(JoinPoint jp){
		String name = jp.getSignature().getName();
		logger.debug("method "+name+" in use " + jp.getTarget().getClass().getName());
		logger.debug("Since it is a save method.. checking if there is an active Transaction");
		if(!TransactionSynchronizationManager.isActualTransactionActive()){
			String message = "No transaction found at service " + name + " method in "+jp.getTarget().getClass().getName()+" class.";
			logger.error(message);
			throw new RuntimeException(message);
		}
		logger.debug("Found an active Transaction.. so good for a database trip");
	}
	@Around("execution(* com.gs.core.service.ServiceFacade+.*(*))")
	public void logTimer(ProceedingJoinPoint pjp) throws Throwable{
		String name = pjp.getSignature().getName();
		Date before = new Date();
		pjp.proceed();
		Date after = new Date();
		long timeTaken = (after.getTime()-before.getTime());
		logger.debug("The method " + name + " took " + timeTaken + " ms. to execute.");
		
	}	
}
